package com.jingchen.pulltorefresh;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.ListView;

/**
 * 支持上拉和下拉刷新，且带有header的ListView
 *
 */
public class PullableHeaderListView extends ListView implements Pullable
{
    // 滑动距离及坐标
    private float xDistance, yDistance, xLast, yLast;

    public PullableHeaderListView(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
    }

    public PullableHeaderListView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
    }

    public PullableHeaderListView(Context context)
    {
        super(context);
    }

    //处理listview与viewpager冲突问题
    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev)
    {
        switch (ev.getAction())
        {
            case MotionEvent.ACTION_DOWN:// 按下
                // 重新初始化数值
                xDistance = yDistance = 0f;
                xLast = ev.getX();
                yLast = ev.getY();
                break;
            case MotionEvent.ACTION_MOVE:// 松开
                final float moveX = ev.getX();
                final float moveY = ev.getY();

                xDistance += Math.abs(moveX - xLast);
                yDistance += Math.abs(moveY - yLast);
                xLast = moveX;
                yLast = moveY;

                if (xDistance > yDistance)
                {
                    return false; // 表示向下传递事件
                }
        }

        return super.onInterceptTouchEvent(ev);
    }

    @Override
    public boolean canPullDown()
    {
        if (getCount() == 0)
        {
            // 没有item的时候也可以下拉刷新
            return true;
        } else if (getFirstVisiblePosition() == 0
                && getChildAt(0).getTop() >= 0)
        {
            // 滑到ListView的顶部了
            return true;
        } else
            return false;
    }

    @Override
    public boolean canPullUp()
    {
        if (getCount() == 0)
        {
            // 没有item的时候也可以上拉加载
            return true;
        } else if (getLastVisiblePosition() == (getCount() - 1))
        {
            // 滑到底部了
            if (getChildAt(getLastVisiblePosition() - getFirstVisiblePosition()) != null
                    && getChildAt(
                    getLastVisiblePosition()
                            - getFirstVisiblePosition()).getBottom() <= getMeasuredHeight())
                return true;
        }
        return false;
    }
}
